package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;

import java.util.LinkedList;

public class ValidParentheses {

    /**
     * 利用栈存放括号左边，遇到配对的右边就弹出
     * 配对过程中，如果栈顶部和字符不匹配或者栈为空，说明s不是有效字符串
     * 如果配对完成后，栈中仍有字符，说明左括号多了，s 也不是有效字符串
     *
     * @param s
     *  1 <= s.length <= 104
     *  s 仅由括号 '()[]{}' 组成
     */
    public boolean isValid(String s) {
        LinkedList<Character> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); ++i){
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{'){
                stack.push(c);
            } else {
                if (stack.isEmpty()){
                    return false;
                }
                char last = stack.pop();
                if (!((last == '(' && c == ')') || (last == '[' && c == ']') || (last == '{' && c == '}'))){
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        String s = "([)]";
        boolean valid = new ValidParentheses().isValid(s);
        Assert.isTrue(!valid);
    }

}
